package com.example.cemenghuii.controller;

import com.example.cemenghuii.dto.ApiResponse;
import com.example.cemenghuii.service.FileService;
import com.example.cemenghuii.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
@CrossOrigin(origins = "*")
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 上传图片
     */
    @PostMapping("/upload/image")
    public ApiResponse<Map<String, String>> uploadImage(@RequestHeader("Authorization") String token,
                                                        @RequestParam("file") MultipartFile file) {
        try {
            // 验证token
            String jwt = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwt)) {
                return ApiResponse.unauthorized("Token无效");
            }

            String filePath = fileService.uploadImage(file);
            Map<String, String> result = new HashMap<>();
            result.put("filePath", filePath);
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", String.valueOf(file.getSize()));
            result.put("fileType", "image");

            return ApiResponse.success("图片上传成功", result);
        } catch (IOException e) {
            return ApiResponse.error("图片上传失败：" + e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传视频
     */
    @PostMapping("/upload/video")
    public ApiResponse<Map<String, String>> uploadVideo(@RequestHeader("Authorization") String token,
                                                        @RequestParam("file") MultipartFile file) {
        try {
            // 验证token
            String jwt = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwt)) {
                return ApiResponse.unauthorized("Token无效");
            }

            String filePath = fileService.uploadVideo(file);
            Map<String, String> result = new HashMap<>();
            result.put("filePath", filePath);
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", String.valueOf(file.getSize()));
            result.put("fileType", "video");

            return ApiResponse.success("视频上传成功", result);
        } catch (IOException e) {
            return ApiResponse.error("视频上传失败：" + e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传文档
     */
    @PostMapping("/upload/document")
    public ApiResponse<Map<String, String>> uploadDocument(@RequestHeader("Authorization") String token,
                                                           @RequestParam("file") MultipartFile file) {
        try {
            // 验证token
            String jwt = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwt)) {
                return ApiResponse.unauthorized("Token无效");
            }

            String filePath = fileService.uploadDocument(file);
            Map<String, String> result = new HashMap<>();
            result.put("filePath", filePath);
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", String.valueOf(file.getSize()));
            result.put("fileType", "document");

            return ApiResponse.success("文档上传成功", result);
        } catch (IOException e) {
            return ApiResponse.error("文档上传失败：" + e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 通用文件上传
     */
    @PostMapping("/upload")
    public ApiResponse<Map<String, String>> uploadFile(@RequestHeader("Authorization") String token,
                                                       @RequestParam("file") MultipartFile file,
                                                       @RequestParam(required = false, defaultValue = "files") String folder) {
        try {
            // 验证token
            String jwt = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwt)) {
                return ApiResponse.unauthorized("Token无效");
            }

            String filePath = fileService.uploadFile(file, folder);
            String fileType = fileService.getFileType(file.getContentType());

            Map<String, String> result = new HashMap<>();
            result.put("filePath", filePath);
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", String.valueOf(file.getSize()));
            result.put("fileType", fileType);
            result.put("contentType", file.getContentType());

            return ApiResponse.success("文件上传成功", result);
        } catch (IOException e) {
            return ApiResponse.error("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 智能文件上传（根据文件类型自动分类）
     */
    @PostMapping("/upload/auto")
    public ApiResponse<Map<String, String>> uploadFileAuto(@RequestHeader("Authorization") String token,
                                                           @RequestParam("file") MultipartFile file) {
        try {
            // 验证token
            String jwt = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwt)) {
                return ApiResponse.unauthorized("Token无效");
            }

            String filePath = fileService.uploadFileByType(file);
            String fileType = fileService.getFileType(file.getContentType());

            Map<String, String> result = new HashMap<>();
            result.put("filePath", filePath);
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", String.valueOf(file.getSize()));
            result.put("fileType", fileType);
            result.put("contentType", file.getContentType());

            return ApiResponse.success("文件上传成功", result);
        } catch (IOException e) {
            return ApiResponse.error("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete")
    public ApiResponse<Void> deleteFile(@RequestHeader("Authorization") String token,
                                        @RequestParam String filePath) {
        try {
            // 验证token
            String jwt = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwt)) {
                return ApiResponse.unauthorized("Token无效");
            }

            boolean success = fileService.deleteFile(filePath);
            if (success) {
                return ApiResponse.success("文件删除成功");
            } else {
                return ApiResponse.error("文件删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除文件
     */
    @DeleteMapping("/batch-delete")
    public ApiResponse<Void> deleteFiles(@RequestHeader("Authorization") String token,
                                         @RequestBody List<String> filePaths) {
        try {
            // 验证token
            String jwt = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwt)) {
                return ApiResponse.unauthorized("Token无效");
            }

            boolean success = fileService.deleteFiles(filePaths);
            if (success) {
                return ApiResponse.success("文件批量删除成功");
            } else {
                return ApiResponse.error("部分文件删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filePath) {
        try {
            String fullPath = fileService.getFullPath(filePath);
            File file = new File(fullPath);

            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(file);
            String contentType = Files.probeContentType(Paths.get(fullPath));
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 文件预览
     */
    @GetMapping("/preview")
    public ResponseEntity<Resource> previewFile(@RequestParam String filePath) {
        try {
            String fullPath = fileService.getFullPath(filePath);
            File file = new File(fullPath);

            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(file);
            String contentType = Files.probeContentType(Paths.get(fullPath));
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + file.getName() + "\"")
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 检查文件是否存在
     */
    @GetMapping("/exists")
    public ApiResponse<Map<String, Boolean>> checkFileExists(@RequestParam String filePath) {
        try {
            boolean exists = fileService.fileExists(filePath);
            Map<String, Boolean> result = Map.of("exists", exists);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("检查文件失败：" + e.getMessage());
        }
    }

    /**
     * 获取文件信息
     */
    @GetMapping("/info")
    public ApiResponse<Map<String, Object>> getFileInfo(@RequestParam String filePath) {
        try {
            String fullPath = fileService.getFullPath(filePath);
            File file = new File(fullPath);

            if (!file.exists()) {
                return ApiResponse.notFound("文件不存在");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("fileName", file.getName());
            result.put("fileSize", file.length());
            result.put("lastModified", file.lastModified());
            result.put("isDirectory", file.isDirectory());
            result.put("canRead", file.canRead());
            result.put("canWrite", file.canWrite());

            String contentType = Files.probeContentType(Paths.get(fullPath));
            result.put("contentType", contentType);
            result.put("fileType", fileService.getFileType(contentType));

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取文件信息失败：" + e.getMessage());
        }
    }
}